<template>
  <view class="upload-wrapper" @click="chooseImage">
    <!-- 已选图片展示 -->
    <view class="image-container" v-if="previewImage">
      <image :src="previewImage" mode="aspectFill" class="upload-image" />
      <!-- 删除按钮（右上角） -->
      <view class="delete-btn" @click.stop="removeImage">
        <up-icon name="close" size="11" color="#fff"></up-icon>
      </view>
    </view>

    <!-- 上传按钮 -->
    <view class="upload-btn flex-cc" v-else>
      <image src="../../static/img/vector-icon.png"></image>
      <view class="upload-btn-text">{{ title }}</view>
    </view>
  </view>

</template>
<script setup>
import { ref, reactive } from "vue"
import { uploadFileRequest } from "../../reuqest/request"
const props = defineProps({
  title: {
    type: String,
    default: '上传图片'
  },
  type: {
    type: String,
    default: ""
  }
})
const emit = defineEmits(['upload'])

const previewImage = ref('')

const removeImage = () => {
  previewImage.value = '';
  emit('upload', { url: '', uuid: '', type: props.type })
};

const chooseImage = () => {
  console.log('chooseImage')
  uni.chooseImage({
    count: 1, // 可选择张数
    success: (res) => {
      const filePath = res.tempFilePaths[0]
      // 上传文件
      uploadFileRequest("/wx-operation/api/v1/bm/file/upload", filePath, 'file').then(res => {
        console.log('上传成功', res)
        if (res.bizCode === "00000") {
          previewImage.value = filePath
          emit('upload', { url: res.data.url, uuid: res.data.uuid, type: props.type })
        }
      })
    }
  })
}
</script>
<style lang="scss" scoped>
.upload-btn {
  width: 300rpx;
  height: 180rpx;
  gap: 16rpx;
  background-color: #F8F8F8;
  border-radius: 20rpx;
  position: relative;

  image {
    width: 138rpx;
    height: 112rpx;
  }

  .upload-btn-text {
    position: absolute;
    bottom: 36rpx;
    left: 50%;
    transform: translateX(-50%);
  }
}

.image-container {
  position: relative;
  width: 100%;
  height: 100%;
  border-radius: 20rpx;
  // overflow: hidden;
}

.delete-btn {
  position: absolute;
  top: -7rpx;
  right: -7rpx;
  width: 40rpx;
  height: 40rpx;
  background-color: rgba(0, 0, 0, 0.6);
  border-radius: 50%;
  z-index: 10;
  display: flex;
  align-items: center;
  justify-content: center;
}

.upload-image {
  width: 300rpx;
  height: 180rpx;
  border-radius: 20rpx;
}
</style>
